odoo.define('web_datetime.basic_fields', function (require) {
"use strict";

var translation = require('web.translation');
var DateWidget = require("web.datepicker").DateWidget;
var basic_fields = require("web.basic_fields");
var registry = require('web.field_registry');

var _t = translation._t;

var KeyDownMixin = {
    async _onKeydown(ev) {
        this._super(...arguments);
        if (ev.which === $.ui.keyCode.ENTER) {
            var value = this.datewidget._formatQuickValue(this.$input.val());
            if (value) {
                var val = this.formatValue(value);
                this.$input.val(val);
            }
            await this._setValue(this.$input.val());
            this._render();
        }
    },
    
    formatValue: function (val) {
        return this.datewidget._formatStr(val);
    }
};

var FieldDate = basic_fields.FieldDate.extend(KeyDownMixin, {

});

var FieldDateTime = basic_fields.FieldDateTime.extend(KeyDownMixin, {
    formatValue: function (val) {
        val.add(-this.getSession().getTZOffset(val), 'minutes');
        return this.datewidget._formatStr(val);
    }
});


registry.add('date', FieldDate);
registry.add('datetime', FieldDateTime);

DateWidget.include({
    start: function () {
        this._super.apply(this, arguments);
        if (this.$('input.o_datepicker_input')) {
            this.$('input.o_datepicker_input').attr('autocomplete', 'off');
        }
    },
    getValue: function () {
        var value = this._formatQuickValue(this.$input.val());
        if (value){
            return value;
        }
        return this._super.apply(this, arguments);
    },
    _formatQuickValue: function(val) {
        if (!val || val.indexOf("-") < 0) {
            return false;
        }
        var isDatetime = this.type_of_date === 'datetime';
        var timeFormat = "HH:mm:ss";
        var format = ["YYYY-MM-DD", "MM-DD"];
        if (isDatetime) {
            format = ["YYYY-MM-DD " + timeFormat,
                    "MM-DD " + timeFormat,
                    "YYYY-MM " + timeFormat];
            val += ' ' + moment().format(timeFormat);
        }
        var value = moment(val, format);
        this.$el.datetimepicker('date', value || null);
        return value;
    },
    _formatStr: function(dateTimeVal){
        return dateTimeVal.format(this.options.format);
    }
});


});